package com.weizhi.business.controller.admin;

import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageInfo;
import com.weizhi.server.dto.ResponseDto;
import com.weizhi.server.dto.CourseDto;
import com.weizhi.server.entity.CourseContent;
import com.weizhi.server.service.CourseService;
import com.weizhi.server.util.JsonUtil;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

@RestController
@RequestMapping("admin/course")
public class CourseController {

    private final static Logger logger = LoggerFactory.getLogger(CourseController.class);

    @Autowired
    private CourseService courseService;

    @RequestMapping("list")
    public ResponseDto list(HttpServletRequest req) {
        JSONObject param = JsonUtil.convertRequest(req);
        logger.info("courseController-list, param={}", param);
        PageInfo pageInfo = courseService.list(param);
        return ResponseDto.createBySuccess(pageInfo);
    }

    @RequestMapping("save")
    public ResponseDto save(@RequestBody CourseDto course) {
        logger.info("courseController-save, course={}", course);
        /*
            前端进行参数校验：减少无用请求占用服务器资源
            后端进行参数校验：防止用户使用非浏览器进行访问，没有进行参数校验
            后端参数校验失败时不返回具体信息，因为后端校验失败说明是前端校验出bug或者是非浏览器访问
         */

        if(StringUtils.isBlank(course.getName()))
            throw new RuntimeException("请求参数异常");
        courseService.save(course);
        return ResponseDto.createBySuccess();
    }

    @DeleteMapping("/delete/{id}")
    public ResponseDto delete(@PathVariable Long id) {
        logger.info("courseController-delete, id={}", id);
        courseService.delete(id);
        return ResponseDto.createBySuccess();
    }

    @GetMapping("/getContent/{id}")
    public ResponseDto getContent(@PathVariable Long id) {
        logger.info("courseController-getContent, id={}", id);
        CourseContent courseContent = courseService.getContent(id);
        return ResponseDto.createBySuccess(courseContent);
    }

    @RequestMapping("/saveContent")
    public ResponseDto saveContent(@RequestBody CourseContent courseContent) {
        logger.info("courseController-saveContent, param={}", courseContent);
        courseService.saveContent(courseContent);
        return ResponseDto.createBySuccess();
    }
}

